package com.example.tuter.fragment;

import static com.example.tuter.util.ssfwUtils.CourseUtil.setTable;
import static com.example.tuter.util.ssfwUtils.SSFWUtils.initTable;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.tuter.MyApplication;
import com.example.tuter.R;
import com.example.tuter.activity.WebViewActivity;
import com.example.tuter.entity.SemesterPair;
import com.example.tuter.fragment.entity.CoursesKB;
import com.example.tuter.fragment.entity.TimeSemester;
import com.example.tuter.util.Constant;
import com.example.tuter.util.CookieUtil;
import com.example.tuter.util.SPUtils;
import com.example.tuter.util.ToastUtil;
import com.example.tuter.util.httpUtil.HttpFunction.SSFWAPI;
import com.example.tuter.util.httpUtil.RetrofitFactory;
import com.example.tuter.util.ssfwUtils.CourseUtil;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class FragmentXXMH extends BaseFragment {
    private static final String TAG = FragmentXXMH.class.getSimpleName();
    private GridLayout gridLayout;
    private View choose_week_text;
    private String chooseSemester = Constant.CUR_SEMESTER;

    private TimeSemester timeSemester = new TimeSemester();


    private View re_login_btn;
    private SSFWAPI ssfwapi;


    //保存课程
    private CoursesKB coursesKB = new CoursesKB();
    private View re_course_btn;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        Retrofit r = RetrofitFactory.getSchoolInstance();
        ssfwapi = r.create(SSFWAPI.class);

    }

    @Override
    public void onStart() {
        super.onStart();
        setCourse(Constant.CUR_SEMESTER);
        initSemesterArray();
    }

    @Override
    public void onResume() {
        super.onResume();
        //当展示该页面时，会再次调用该函数
        if (coursesKB == null) {
            //点击获取其他时间段的课表后，会把课表清空，根据选择的时间尝试重新获取课表
            setCoursesFromSchool(chooseSemester);
        }
    }

    /**
     * 在这个方法中初始化当前周数和学期，并获取课表信息，其实应该是信息门户页默认显示课程表，
     */
    private void getCurTime() {

        //应该能够计算得到第一周的周数，今天是一年的第几周，减去官网返回的第几周，得到第一周是多少，存储这个第一周的周数，
        // 之后就是通过登录时得到的第一周，相减得到当前周数，直到超过20，就清空。
        //如果已经初始化该学期第一周，应该可以通过现在的日期获得现在是该学期第几周，如果超过20周，就清掉，需要用户重新登录
        //这里先放着。等完成了其他功能再开个分支完成这个点。


        //先获取本地信息，不行再获取服务器信息，再不行再请求信息门户，同时提供主动刷新，获取信息门户的按钮，并同步各端信息


    }


    private void initSemesterArray() {
        //本地加载
        timeSemester = SPUtils.getSemesters(MyApplication.getContext());
        if (timeSemester != null) {
            return;
        }
        Call<ArrayList<SemesterPair>> semesterCall = ssfwapi.getSemesters(SSFWAPI.Semester_url, CookieUtil.getCookieFromCookieClass(Constant.schoolCookie));
        semesterCall.enqueue(new Callback<ArrayList<SemesterPair>>() {
            @Override
            public void onResponse(Call<ArrayList<SemesterPair>> call, Response<ArrayList<SemesterPair>> response) {
                ArrayList<SemesterPair> semesterPairs = response.body();
                if (semesterPairs == null) {
                    ToastUtil.showToastShort(TAG,"网络错误，重新尝试，可能需要重新登录");
                    return;
                }
                //持久化
                timeSemester = new TimeSemester(semesterPairs);
                SPUtils.setSemesters(MyApplication.getContext(), timeSemester);
                //更新ui
                setSemesterClick();
            }

            @Override
            public void onFailure(Call<ArrayList<SemesterPair>> call, Throwable t) {
                ToastUtil.showToastShort(TAG,"网络错误，重新尝试，可能需要重新登录");
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_xxmh_courses, container, false);
    }

    @Override
    protected void initData() {

    }


    //初始化课表,默认先获得当前学期的课表
    private void setCourse(String semester) {
        CoursesKB coursesKB = getCoursesFromLocal(semester);
        getActivity().runOnUiThread(() -> {
            if (coursesKB != null) {
                //本地读取课表信息
                //更新课表
                setTable(gridLayout, coursesKB, MyApplication.getContext());
                FragmentXXMH.this.coursesKB = coursesKB;
            } else if (Constant.schoolCookie != null) {
                //从信息门户加载
                setCoursesFromSchool(semester);
            }
        });



    }

    //从信息门户获取课表，并刷新本地缓存
    private void setCoursesFromSchool(String semester) {
        if (semester == null) return;
        Retrofit r = RetrofitFactory.getSchoolInstance();
        SSFWAPI ssfwapi = r.create(SSFWAPI.class);
        String url = SSFWAPI.Kcbxx_pre + semester + ".do";

        Call<ResponseBody> call = ssfwapi.getKcbxx(url, CookieUtil.getCookieFromCookieClass(SPUtils.getSchoolCookie(MyApplication.getContext())));
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                ResponseBody body = response.body();

                try {
                    coursesKB = CourseUtil.getCourse(body.string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(coursesKB==null){
                    ToastUtil.showToastShort(TAG,"获取课表失败了，可能是信息门户cookie失效");
                    return;
                }
                //持久化
                SPUtils.putCourse(MyApplication.getContext(), semester, coursesKB);
                //更新ui
                setTable(gridLayout, coursesKB, MyApplication.getContext());

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                ToastUtil.showToastShort(TAG,"获取课表失败了，请检查网络重新尝试");
            }
        });


    }

    private CoursesKB getCoursesFromLocal(String semester) {
        if (semester == null) return null;
        //从SP获取吧
        return SPUtils.getCourseBySemester(MyApplication.getContext(), semester);
    }

    @Override
    protected void bindEvent() {
        if (timeSemester != null) {
            setSemesterClick();
        }
        //重新登录获取cookie
        re_login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, WebViewActivity.class);
                context.startActivity(intent);
            }
        });
        //刷新当前课表
        re_course_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //重新获取当前选择的课程表
                setCoursesFromSchool(chooseSemester);
            }
        });

    }

    private void setSemesterClick() {
        choose_week_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(FragmentXXMH.this.getActivity());
                // 设置标题
                builder.setTitle("选择学期").
                        // 设置可选择的内容，并添加点击事件
                                setItems(timeSemester.getLabels(), (dialog, which) -> {
                            // which代表的是选择的标签的序列号
                            //点击以后重新生成课程表ui，重新获取课程表信息。
                            ToastUtil.showToastShort(TAG,timeSemester.getIds()[which]);
                            //优先获取本地，提供刷新按钮
                            chooseSemester = timeSemester.getIds()[which];


                            setCoursesFromSchool(chooseSemester);

                        }).create().show();

            }
        });
    }

    @Override
    protected void initView(View view) {
        gridLayout = (GridLayout) getActivity().findViewById(R.id.Grid_Layout);
        choose_week_text = getActivity().findViewById(R.id.choose_week_text);
        re_login_btn = getActivity().findViewById(R.id.re_login_btn);

        re_course_btn = getActivity().findViewById(R.id.re_course_btn);
        initTable(getActivity(), gridLayout);

    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_view_post;
    }


}
